<template>
  <div>
    <el-card class="search-card" v-loading="formLoading">
      <BasicForm
        v-if="!formLoading"
        isScalingBtn
        ref="formData"
        formItemWidth="80px"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
        :defaultExpandStatus="false"
      />
    </el-card>
    <el-card class="table-card">
      <BasicTable
        showPagination
        isCustomSort
        :defaultMinWidth="100"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :tableHeight="480"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <el-row slot="content_context" type="flex">
          <el-button
            v-if="showBtn('导出')"
            type="primary"
            size="mini"
            :loading="exportLoading"
            @click="exportMaterialToDoList"
          >
            导出
          </el-button>
          <el-badge
            v-if="showBtn('查询')"
            :value="seniorLinked.skuNos.length || ''"
            style="marginLeft: 10px;"
          >
            <el-button
              type="primary"
              size="mini"
              @click="handleSeniorLinked"
            >
             高级查询
            </el-button>
          </el-badge>
        </el-row>
      </BasicTable>
    </el-card>
    <!-- 高级关联 -->
    <SeniorLinkedDialog
      showClearBtn
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getTableDataBySeniorLinked"
      @clear="clearSeniorResults"
    />
  </div>
</template>
<script>
import BasicForm from '@/pages/stock/components/BasicForm';
// import BasicForm from '@/components/BasicForm';
import BasicTable from '@/components/skusTable';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import skusPage from '@/mixins/commodity/skusPage';
import { initFormItemList, TABALE_COLUMNS } from './constants';
import {
  setAuthBtnId,
  createExcelByExport
} from '@/utils/bizUtils';
import {
  queryAmountLimitService,
  exportAmountLimitService
} from '@/api/stock/upperLowerLimits'
import {
  queryBusinessAreaListService,
  queryBrandListService,
  queryAllCompanyService,
  queryAllCenterService
} from '@/api/public';

export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    BasicTable,
    SeniorLinkedDialog
  },
  data () {
    return {
      formItemList: initFormItemList(),
      formLoading: false,
      formData: {
        categoryUuids: [],
        brandUuid: '',
        companyId: null,
        saleAreaNo: '',
        skuNo: '',
        productName: '',
        upperLimitFrom: null,
        upperLimitTo: null,
        lowerLimitFrom: 0.01,
        lowerLimitTo: null,
        wayToCargo: '', // 0:自进货 1:内部调货
        centerDepartments: []
      },
      tableInfo: {
        list: [],
        columns: TABALE_COLUMNS,
        loading: false,
        selection: []
      },
      pageSizes: [10, 100, 1000],
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }],
        skuNos: [], // 高级关联的结果集
      },
    };
  },
  mounted () {
    this.getSelectData();
    this.getTableData();
  },
  methods: {
    // 高级关联
    handleSeniorLinked () {
      this.seniorLinked.visible = true;
    },
    // 获取表格数据 by 高级关联
    async getTableDataBySeniorLinked (skuNos) {
      this.seniorLinked.skuNos = skuNos
      this.getTableData()
    },
    //
    clearSeniorResults () {
      this.seniorLinked.skuNos = []
    },
    // 查询条件校验
    handleSearchLimit () {
      let canSearch = true;
      const {
        upperLimitFrom,
        upperLimitTo,
        lowerLimitFrom,
        lowerLimitTo
      } = this.formData;
      if (upperLimitFrom && upperLimitTo && upperLimitFrom > upperLimitTo) {
        this.$message.warning('上限起始值不能大于结束值');
        canSearch = false;
      }
      if (lowerLimitFrom && lowerLimitTo && lowerLimitFrom > lowerLimitTo) {
        this.$message.warning('下限起始值不能大于结束值');
        canSearch = false;
      }
      return canSearch;
    },
    // 获取表格数据
    async getTableData () {
      if (this.handleSearchLimit()) {
        const data = {
          ...this.paginationParams,
          ...this.formData,
          skuNos: this.seniorLinked.skuNos
        };
        setAuthBtnId();
        const res = await queryAmountLimitService(data, (state) => {
          this.tableInfo.loading = state;
        });
        if (res?.retData) {
          this.tableInfo.list = res.retData.results;
          this.total = res.retData.totalNum;
        }
      }
    },
    // 导出信息数据
    async exportMaterialToDoList () {
      if (this.handleSearchLimit()) {
        setAuthBtnId();
        const res = await exportAmountLimitService(
          {
            ...this.formData,
            skuNos: this.seniorLinked.skuNos
          },
          (state) => {
            this.exportLoading = state;
          }
        );
        createExcelByExport({ res, excelTitle: '上下限管理列表' });
      }
    },
    // 获取查询条件下拉选项
    getSelectData () {
      this.formLoading = true
      Promise.all([
        this.getBusinessAreaList(),
        this.getBrandList(),
        this.getCompanyList(),
        this.getCenterList(),
      ]).then(([areaData, brandData, companyData, centerData]) => {
        this.formLoading = false
        this.formItemList = initFormItemList(areaData, brandData, companyData, centerData)
      }).catch(() => {
        this.formLoading = false
      })
    },
    // 管理区域
    async getBusinessAreaList () {
      const res = await queryBusinessAreaListService({});
      if (res?.retData) {
        const areaList = res.retData.map(item => {
          return {
            value: item.areaCode,
            label: item.areaName
          }
        })
        return areaList;
      }
    },
    // 获取品牌集合
    async getBrandList () {
      const res = await queryBrandListService({});
      if (res?.retData) {
        return res.retData
      }
    },
    // 获取公司集合
    async getCompanyList () {
      const res = await queryAllCompanyService({});
      if (res?.retData) {
        return res.retData
      }
    },
    // 获取归属中心集合
    async getCenterList () {
      const res = await queryAllCenterService({});
      if (res?.retData) {
        const centerList = res.retData.map(item => {
          return {
            value: item.hrDepartmentId,
            label: item.hrDepartmentName
          }
        })
        return centerList
      }
    },
  }
};
</script>
